﻿namespace TfsExtensions.Build.Controls
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Drawing.Design;
    using System.ComponentModel;
    using System.Windows.Forms.Design;
    using TfsExtensions.Build.Activities.Entities;
    using System.Collections.ObjectModel;
    using Microsoft.TeamFoundation.VersionControl.Client;
    using Microsoft.TeamFoundation.Server;
    using System.Windows.Forms;
    using System.Security.Permissions;
    using Microsoft.TeamFoundation.Client;
    using TfsExtensions.Build.Controls;

    public class MetadataEditor : UITypeEditor
    {
        public string InitialServerPath { get; set; }
        public string TfsServerName { get; set; }
        public VersionControlServer TfsVersionControlServer { get; set; }
        public ICommonStructureService TfsCommonStructureService { get; set; }

        //[PermissionSet(SecurityAction.LinkDemand, Name = "FullTrust")]
        public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context)
        {
            foreach (Attribute attribute in context.PropertyDescriptor.Attributes)
            {
                if ((attribute is ReadOnlyAttribute) && ((ReadOnlyAttribute)attribute).IsReadOnly)
                {
                    return UITypeEditorEditStyle.None;
                }
            }

            return UITypeEditorEditStyle.Modal;
        }


        public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
        {
            if (provider != null)
            {
                IWindowsFormsEditorService service = (IWindowsFormsEditorService)provider.GetService(typeof(IWindowsFormsEditorService));
                if (service == null)
                {
                    return value;
                }
                
                var assemblyInfoCollection = (Collection<AssemblySettings>)value;
                using (DialogMetadataRulesManager editor = new DialogMetadataRulesManager(){ MetadataCollection = assemblyInfoCollection})
                {
                    editor.TfsVersionControlServer = (VersionControlServer)provider.GetService(typeof(VersionControlServer));
                    editor.TfsCommonStructureService = (ICommonStructureService)provider.GetService(typeof(ICommonStructureService));

                    editor.TfsVersionControlServer.TeamProjectCollection.EnsureAuthenticated();
                    editor.TfsServerName = editor.TfsVersionControlServer.TeamProjectCollection.Name;
                    
                    editor.MetadataCollection = assemblyInfoCollection;

                    var tfs = SetupConnection(editor.TfsVersionControlServer.TeamProjectCollection.Name);
                    if (tfs != null)
                    {
                        editor.TfsVersionControlServer = (VersionControlServer)tfs.GetService(typeof(VersionControlServer));
                        editor.TfsCommonStructureService = (ICommonStructureService)tfs.GetService<ICommonStructureService>();
                        editor.TfsServerName = tfs.Name;
                    }

                    if (service.ShowDialog(editor) == DialogResult.OK)
                    {
                        value = editor.MetadataCollection;
                    }
                }
            }
            return value;
        }

        private TfsTeamProjectCollection SetupConnection(string tfsServerUri)
        {
            TfsTeamProjectCollection tfs = null;
            RegisteredProjectCollection registeredProject = null;
            ICredentialsProvider uiCredentialProvider = new UICredentialsProvider();

            try
            {
                RegisteredProjectCollection[] collections = RegisteredTfsConnections.GetProjectCollections();
                if (collections != null)
                {
                    foreach (RegisteredProjectCollection collection in collections)
                    {
                        if (String.Compare(tfsServerUri, collection.Name) == 0)
                        {
                            registeredProject = collection;
                        }
                    }
                }

                tfs = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(registeredProject, uiCredentialProvider);
                tfs.Authenticate();
            }
            catch
            {
                tfs = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(registeredProject, uiCredentialProvider);
                try
                {
                    tfs.Authenticate();
                }
                catch
                {
                    tfs = null;
                }
            }

            return tfs;
        }
    }
}
